<template>
    <div class="h-full overflow-hidden flex flex-col">
        <div class="flex-1 overflow-auto pt-[26px] pb-[80px] px-[56px]">
            <div class="flex flex-row items-center gap-[10px]">
                <div class="bg-theme w-1 h-5 rounded-xs"></div>
                <span class="text-theme text-[18px] font-bold">公司基本信息</span>
            </div>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]">
                <p class="text-sm text-primary">填写公司基本信息有什么用？</p>
                <p class="text-sm text-secondary mt-2">丰富的公司介绍，能获得更多求职者的青睐，为你的职位带来更多查看与沟通。</p>
            </section>
            <section class="mt-6">
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">公司Logo：</label>
                    <div class="flex flex-row items-end gap-3">
                        <div @click="uploadLogo()" style="width: 80px; height: 80px;"
                            :class="uploadingLogo ? 'cursor-not-allowed' : 'cursor-pointer'"
                            class="relative rounded-sm border border-dashed border-[#DDDDDD] hover:border-theme bg-[#FCFBFF]"
                        >
                            <div class="flex flex-col justify-center items-center size-full text-[#ACAEB2]">
                                <template v-if="uploadingLogo">
                                    <LoadingOutlined style="color: var(--color-theme); font-size: 20px;" />
                                    <span class="text-sm text-theme mt-1">上传中...</span>
                                </template>
                                <template v-else>
                                    <GpFontIcon name="icon-shangchuan" class="!text-[32px] !leading-none" />
                                    <span class="text-sm ">上传图标</span>
                                </template>
                            </div>
                            <div class="size-full absolute inset-0 group" v-if="formState.logo">
                                <img :src="formState.logo" width="100%" height="100%" class="size-full object-cover block"/>
                                <div class="absolute inset-0 bg-black/60 hidden group-hover:flex flex-col justify-center items-center box-border text-white">
                                    <GpFontIcon name="icon-zhongxinshangchuan" class="!text-[32px] !leading-none" />
                                    <span class="text-sm ">重新上传</span>
                                </div>
                            </div>
                        </div>
                        <div class="flex flex-row items-center gap-1 text-third" v-if="formState.logo">
                            <GpFontIcon name="icon-zhuyi" />
                            <span class="text-xs">
                                若不想使用当前logo，可以
                                <span class="touchable-opacity text-secondary pl-[2px]" @click="handleUseDefLogo()">恢复默认</span>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">品牌名称：</label>
                    <div class="w-[320px]">
                        <a-input placeholder="请输入品牌名称" style="height: 36px;" v-model:value="formState.name"/>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">公司全称：</label>
                    <div class="w-[320px]">
                        <a-input placeholder="请输入公司全称" style="height: 36px;" v-model:value="formState.fullName"/>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">所在行业：</label>
                    <div class="w-[320px]">
                        <a-input placeholder="请输入所在行业" style="height: 36px;" v-model:value="formState.industry"/>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">融资阶段：</label>
                    <div class="w-[320px]">
                        <a-select placeholder="请选择融资阶段" style="height: 36px; width: 100%;" class="fuck-select" :options="stageOptions" v-model:value="formState.stage"/>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none">人员规模：</label>
                    <div class="w-[320px]">
                        <a-select placeholder="请选择人员规模" style="height: 36px; width: 100%;" class="fuck-select" :options="scaleOptions" v-model:value="formState.scale"/>
                    </div>
                </div>
                <div class="flex flex-row items-start gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none mt-2">公司地址：</label>
                    <div class="box-border">
                        <div class="flex flex-row items-center gap-2">
                            <a-cascader v-model:value="formState.area" :options="areaOptions" :fieldNames placeholder="请选择区域" style="height: 36px; width: 172px;" @change="handleAreaChange" />
                            <a-input placeholder="请输入详细地址" style="height: 36px; width: 320px;" v-model:value="formState.address" @blur="handleLocate()"/>
                        </div>
                        <div class="w-[500px] h-[286px] rounded-sm box-border mt-4" v-if="center">
                            <BaiduMap
                                v-bind="defaultMapProps"
                                :center="center"
                                class="map"
                                @ready="handleMapReady"
                                @zoomend="syncCenter"
                            >
                                <BmMarker :position="center" v-if="mapReady" />
                            </BaiduMap>
                        </div>
                        <p class="mt-[14px] text-sm text-third">请确认地图定位是否准确，如有误，请拖拽地图找到正确定位</p>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-[14px] mb-6">
                    <label class="text-primary text-sm flex-none"><span class="invisible">禁</span>联系人：</label>
                    <div class="flex flex-row items-center gap-2">
                        <a-input placeholder="请选择联系人姓名" style="height: 36px; width: 172px;" v-model:value="formState.contactName"/>
                        <a-input placeholder="请输入联系人电话" style="height: 36px; width: 320px;" v-model:value="formState.contactPhone"/>
                    </div>
                </div>
            </section>
        </div>
        <div class="px-[56px] box-border h-[88px] border-t border-solid border-t-[#EEEEEE] relative">
            <div class="flex flex-row justify-end items-center h-full 2xl:w-[750px]">
                <a-button type="primary" class="rounded-sm w-[124px]" size="large" :loading="uploadingLogo || submiting" @click="handleSave()">
                    保存
                </a-button>
            </div>
            <div class="text-[#ACAEB2] text-sm flex flex-row items-center gap-1 cursor-pointer absolute left-[56px] top-[34px]">
                上传注意事项
                <GpFontIcon name="icon-yiwen1"/>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { BaiduMap, BmMarker } from 'vue-baidu-map-3x';
import { postCompanyinfoBaseinfo } from '@/api/siderBar/companyInfo';
import { defaultMapProps } from '@/constants/comp-setting';
import type { CompanyBaseInfoRequest, CompanyInfoResult } from '@/api/siderBar/model';
import { uploadFile } from '@/api/upload';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import type { DefaultOptionType, ValueType } from 'ant-design-vue/es/vc-cascader/Cascader';
defineOptions({
    name: "CompanyBasicInfo"
})
interface FormState extends CompanyBaseInfoRequest {
    area?: string[]
}
type Props = Partial<CompanyInfoResult>
const props = defineProps<Props>()
const emit = defineEmits<{
    refresh: []
}>()
const submiting = ref(false)
const formState = ref(getInitialState())
const { uploadAction: uploadLogo, uploading: uploadingLogo } = useUpload({
    receiveResults([logo]) {
        if (logo) {
            formState.value.logo = logo.fullName
        }
    },
    globalLoading: false
})
const { data: areaOptions, refreshAsync } = useFetchAreas()
const fieldNames = {
    label: "name",
    value: "id",
    children: "children"
}
const center = ref<{
    lng: number;
    lat: number;
}>();
let mapInstance: any = null;
let geoInstance: any = null;
let cityName: MaybeUndefined<string> = void 0;
const mapReady = ref(false)
function handleMapReady({ BMap, map }: any) {
  mapInstance = map;
  geoInstance = new BMap.Geocoder();
  nextTick(() => {
    mapReady.value = true
  })
}
const syncCenter = (e: any) => {
  if (!center.value || !mapReady.value) return;
  const point = new window.BMap.Point(center.value.lng, center.value.lat);
  e.target.centerAndZoom(point, e.target.getZoom());
};
function handleLocate() {
  if (!formState.value.areaId) {
    return message.warn('请选择地区');
  }
  if (!formState.value.address) {
    return message.warn('请输入详细地址');
  }
  geoInstance.getPoint(
    formState.value.address,
    (point: any) => {
      if (point) {
        center.value = {
          lng: point.lng,
          lat: point.lat,
        };
        formState.value.lng = point.lng;
        formState.value.lat = point.lat;
        mapInstance.centerAndZoom(point, defaultMapProps.zoom);
      } else {
        Modal.error({
          title: '定位失败',
          content: '请输入更为详细的位置信息便于更好的定位',
        });
      }
    },
    cityName,
  );
}
function handleAreaChange(_: ValueType, selectOptions: DefaultOptionType[]) {
 if (selectOptions) {
    const [_, city, area] = selectOptions
    formState.value.areaId = area.id
    cityName = city.name
 } else {
    formState.value.areaId = void 0
    cityName = void 0
 }
}
watch(() => props.baseInfo, () => {
    populate()
}, {
    immediate: true
})
const stageOptions: IOption<string>[] = [
    { value: "未融资", label: "未融资" },
    { value: "天使轮", label: "天使轮" },
    { value: "A轮", label: "A轮" },
    { value: "B轮", label: "B轮" },
    { value: "C轮", label: "C轮" },
    { value: "D轮及以上", label: "D轮及以上" },
    { value: "已上市", label: "已上市" },
    { value: "不需要融资", label: "不需要融资" },
]
const scaleOptions: IOption<string>[] = [
    { value: "0-20人", label: "0-20人" },
    { value: "20-99人", label: "20-99人" },
    { value: "100-499人", label: "100-499人" },
    { value: "500-999人", label: "500-999人" },
    { value: "1000-9999人", label: "1000-9999人" },
    { value: "10000人以上", label: "10000人以上" },
]
const lsKey = getLsKey("company_def_logo")
const defLogo = withPublicPath("/images/company-def-logo.png")
function getCachedDefLogo() {
    return localStorage.getItem(lsKey)
}
function setCachedDefLogo(value: string) {
    return localStorage.setItem(lsKey, value)
}
function getInitialState() {
    return <FormState>{}
}
function populate() {
    if (props.baseInfo) {
        formState.value = {
            ...props.baseInfo,
        }
        const { lng, lat } = props.baseInfo
        if (lng && lat) {
            center.value = {
                lng,
                lat
            }
        } else {
            center.value = defCenter
        }
        patchArea()
    } else {
        center.value = defCenter
        formState.value = getInitialState()
    }
}
async function patchArea() {
    const { areaId } = formState.value
    if (!isSetValue(areaId)) return
    let _areaOptions = toValue(areaOptions)
    if (!_areaOptions) {
        await refreshAsync()
        _areaOptions = toValue(areaOptions)!
    }
    for (let i = 0; i< _areaOptions.length; i++) {
        const p = _areaOptions[i]
        for (let j = 0; j < p.children!.length; j++) {
            const c = p.children![j]
            for (let m = 0; m < c.children!.length; m++) {
                const a = c.children![m]
                if (a.id === areaId) {
                    formState.value.area = [p.id, c.id, areaId]
                    cityName = c.name
                    return
                }
            }
        }
    }
}
function handleUseDefLogo() {
    formState.value.logo = defLogo
}
async function handleSave() {
    try {
        submiting.value = true
        const { area, ...state } = toValue(formState)
        if (!state.name) {
            message.error('请输入品牌名称')
            return
        }
        if (!state.fullName) {
            message.error('请输入公司全称')
            return
        }
        if (!state.logo) {
            state.logo = defLogo
        }
        if (state.logo === defLogo) {
            const cached = getCachedDefLogo()
            if (cached) {
                state.logo = cached
            } else {
                const blob = await getBlobFromUrl(defLogo)
                const { fullName } = await uploadFile(new File([blob], "defLogo.png", { type: blob.type }))
                state.logo = fullName
                setCachedDefLogo(fullName)
            }
        }
        await postCompanyinfoBaseinfo(state)
        submiting.value = false
        message.success('保存成功')
        emit('refresh')
    } catch (error) {
        console.log(error)
        submiting.value = false
    }
}
</script>
<style lang="less" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>